# 负责准备页面内容数据 + 页面路由
from django.http import HttpResponse
from django.shortcuts import render

import random
from utils.tencent.sms import send_sms_single

from django.conf import settings

from django import forms
from . import models

from django.core.validators import RegexValidator


def send_sms(request):
    """发送短信
        /app01/send/sms/?tpl=register -> 674961
        /app01/send/sms/?tpl=login    -> 674962
    """
    tpl = request.GET.get('tpl')
    template_id = settings.TENCENT_SMS_TEMPLATE.get(tpl)  # dict的get方法
    if not template_id:
        return HttpResponse('模板不存在')

    code = random.randrange(1000, 9999)  # 四位随机数作为验证码
    res = send_sms_single('15349158668', template_id, [code, ])  # 向指定手机号码发送验证码
    if res['result'] == 0:
        return HttpResponse('发送成功')
    else:
        return HttpResponse(res['errmsg'])


class RegisterModelForm(forms.ModelForm):
    pass_word = forms.CharField(label='密码', widget=forms.PasswordInput())
    confirm_pass_word = forms.CharField(label='重复密码', widget=forms.PasswordInput())
    mobile_phone = forms.CharField(label='手机号',
                                   validators=[RegexValidator(r'(1[3|4|5|6|7|8|9])\d{9}$',
                                                              '手机号格式错误'), ])
    code = forms.CharField(label='验证码')

    class Meta:
        model = models.UserInfo
        fields = ['username', 'email', 'pass_word', 'confirm_pass_word', 'mobile_phone', 'code']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():  # name 是字段名, field 是字段值
            field.widget.attrs['class'] = 'form-control'
            field.widget.attrs['placeholder'] = '请输入%s' % field.label


def register(request):
    form = RegisterModelForm()
    return render(request, 'register.html', {'form': form})
